package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import bean.Employee;
import bean.Person;
import bean.Traveler;
import exception.DAOException;

public class PersonDAOImpl extends DAO  implements PersonDAO {

	@Override
	public Person authenticateUser(String username, String password)
			throws DAOException {
		PreparedStatement stmt = null;
		Connection connection = null;
		Person person = null;
		try {
			connection = getConnection();
			if (connection != null) {
//				/
				
				String SQL = "select * from ars1.person where username = ? and password = ?;";
				stmt = connection.prepareStatement(SQL);
				stmt.setString(1, username);
				stmt.setString(2, password);
				ResultSet resultSet = stmt.executeQuery();
				while (resultSet.next()) {
					
					String type = resultSet.getString("type");
					if(type.equalsIgnoreCase("employee")){
						 person = new Employee();
						// ((Employee)person).setRole(resultSet.getString("role"));
					}else{
						person = new Traveler();
					}
					person.setFirstName(resultSet.getString("first_name"));
					person.setLastName(resultSet.getString("last_name"));
					person.setUserName(resultSet.getString("username"));
					person.setId(resultSet.getLong("id"));
					person.setType(resultSet.getString("type"));
				}

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //Very important step. Never miss out on this!
		finally {
			try{
				stmt.close();
				connection.close();
			}catch(Exception ex){
				
			}
			
		}
		return person;
	}

	@Override
	public boolean checkUser(String username) throws DAOException {
		PreparedStatement stmt = null;
		Connection connection = null;
		boolean found = false;
		try {
			connection = getConnection();
			if (connection != null) {
//				/
				
				String SQL = "select * from ars1.person where username = ? ;";
				stmt = connection.prepareStatement(SQL);
				stmt.setString(1, username);
				
				ResultSet resultSet = stmt.executeQuery();
				while (resultSet.next()) {
					found = true;
				}

			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new DAOException(e.getMessage());
		} //Very important step. Never miss out on this!
		finally {
			try{
				stmt.close();
				connection.close();
			}catch(Exception ex){
				throw new DAOException(ex.getMessage());
			}
			
		}
		return found;
	}

}
